package com.fling.objects;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.fling.Constants;
import com.fling.Locator;
import com.fling.entity.CollisionEntity;

public class Coin extends CollisionEntity {

	protected Animation animation;
	protected TextureRegion[] frames;
	protected TextureRegion currentFrame;
	protected float stateTime;
	public static float SCALE = 0.6F;
	private boolean deleted;

	public float SPEED = 88f;

	public Coin(Vector2 pos) {
		super(1, 4, pos, TYPE.COIN, COIN_PATH, false, true, SCALE);
		// animation
		int cols = 1;
		int rows = 4;
		Texture sheet = sprite.getTexture();
		TextureRegion[][] tmp = TextureRegion.split(sheet, sheet.getWidth() / cols, sheet.getHeight() / rows);
		frames = new TextureRegion[cols * rows];
		int index = 0;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				frames[index++] = tmp[i][j];
			}
		}
		float animTime = 0.25f / (float) (cols * rows);
		animation = new Animation(animTime, frames);
		stateTime = 0f;
		deleted=false;
	}

	@Override
	public void render(SpriteBatch sb) {
		if (!deleted) {
			if (currentFrame != null) {
				sb.draw(currentFrame, body.getPosition().x - currentFrame.getRegionWidth() * 0.5f,
						body.getPosition().y - currentFrame.getRegionHeight() * 0.5f, currentFrame.getRegionWidth() * 0.5f,
						currentFrame.getRegionHeight() * 0.5f, currentFrame.getRegionWidth(), currentFrame.getRegionHeight(), Constants.SCALE * scale
								* Locator.getxSpriteScale(), Constants.SCALE * scale * Locator.getySpriteScale(), 0);
			}
		}
	}

	@Override
	public void update(float delta) {
		if (!deleted) {
			super.update(delta);
			body.setLinearVelocity(0, -SPEED * Locator.getYGameSpeed() * Locator.getOverallGameSpeed() * delta);
			stateTime += delta;
			currentFrame = animation.getKeyFrame(stateTime, true);
			if (!exists) {
				delete();
				deleted = true;
			}
		}
	}

	@Override
	public void collide(CollisionEntity otherBody) {
		if (otherBody.getType().equals(TYPE.HERO)) {
			exists = false;
		}
	}
}
